<!DOCTYPE html>
<html>

<head>
  <title>人脸识别</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0" />
  <script src="https://unpkg.com/vue@3"></script>
  <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
  <script src="https://unpkg.com/element-plus"></script>
  <style>
    .center-container {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 70vh;
    }

    .h1 {
      color: #3f3e3e;
      margin-bottom: 40px;
      /* 与下方进度条的间距 */
    }

    .progress-circle {
      position: relative;
      width: 200px;
      /* 直径大小 */
      height: 200px;
      /* 直径大小 */
    }

    .video {
      width: 185px;
      /* 与el-progress的直径相同 */
      height: 185px;
      /* 与el-progress的直径相同 */
      border-radius: 50%;
      /* 使其成圆形 */
      background-color: #000;
      color: white;
      font-size: 24px;
    }
  </style>
</head>

<body>
  <div id="app">
    <div class="center-container">
      <h1 class="h1">拿起手机，眨眨眼</h1>
      <el-progress v-loading="loading" type="circle" :percentage="progress" status="success" :width="200"
        class="progress-circle" duration=5>
        <video class="video" id="video" playsinline autoplay></video>
      </el-progress>
    </div>
    <el-dialog v-model="centerDialogVisible" title="提示" center>
      <span id="promptContent" v-text="promptContent">
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="this[currentAction]">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <script type="text/javascript" src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
  <script>
    const dingtalkUserId = "{{ dingtalk_user_id }}";
    const personInformationPath = "{{ personInformationPath }}";
    const signOrderNo = "{{ signOrderNo }}"
    const signOrderNos = "{{ signOrderNos }}"
    const userId = "{{ userId }}";

    console.log("dingtalkUserId:", dingtalkUserId);
    console.log("personInformationPath:", personInformationPath);
    console.log("userId:", userId);
    console.log("signOrderNo:", signOrderNo);
    const App = {
      data () {
        return {
          message: "Hello Element Plus",
          progress: 0,
          centerDialogVisible: false,
          promptContent: '订单已创建，请进行人脸识别',
          currentAction: 'createdAction',
          pendingUrl: '',
          loading: false
        };
      },
      methods: {
        countdownToFiveSeconds () {
          const intervalId = setInterval(() => {
            this.progress += 1;
            if (this.progress >= 100) {
              clearInterval(intervalId);
            }
          }, 50);
        },
        async startVideoRecording () {
          navigator.mediaDevices.getUserMedia({
            video: {
              facingMode: "user",
              frameRate: { ideal: 25, max: 30 },
              width: { ideal: 720 },
              height: { ideal: 720 }
            },
            audio: false
          })
            .then(stream => {
              const video = document.getElementById('video');
              video.srcObject = stream;
              video.play();
              // 准备录制
              let mediaRecorder = new MediaRecorder(stream);
              let chunks = [];
              mediaRecorder.ondataavailable = e => chunks.push(e.data);
              const timerId = this.countdownToFiveSeconds();
              // 开始录制
              mediaRecorder.start();
              // 5秒后停止录制
              setTimeout(() => {
                mediaRecorder.stop();
                stream.getTracks().forEach(track => track.stop());
                video.srcObject = null; // 清除视频源，停止显示视频流
              }, 5500);

              // 录制停止
              mediaRecorder.onstop = e => {
                this.loading = true
                const blob = new Blob(chunks, { 'type': 'video/mp4' });
                const fileName = "recorded-video.mp4"; // 指定文件名
                const fileOptions = { type: blob.type, lastModified: new Date().getTime() }; // 指定文件类型和最后修改时间
                const file = new File([blob], fileName, fileOptions);
                this.putObject(file)
              };
            })
            .catch(error => {
              console.error('获取摄像头失败:', error);
            });
        },
        async fetchData () {
          try {
            const response = await fetch("https://api.zjcxjc.cn/api/v1/digital-sign/intention/sign-security-token", {
              method: 'POST', // 或 'POST', 根据你的接口要求
            });
            if (!response.ok) {
              throw new Error('Network response was not ok');
            }
            const { data } = await response.json();
            return data
          } catch (error) {
            console.error('There was a problem with your fetch operation:', error);
          }
        },
        async putObject (file) {
          try {
            const data = await this.fetchData(); // 确保这里是异步获取的数据
            if (data) {
              const client = new OSS({
                region: 'oss-cn-hangzhou',
                bucket: "xu-digital-sign",
                accessKeyId: data.AccessKeyId,
                accessKeySecret: data.AccessKeySecret,
                stsToken: data.SecurityToken,
              });
              if (signOrderNo || signOrderNos) {
                const mp4Url = `${personInformationPath}${userId}.mp4`
                const result = await client.put(mp4Url, file);
                let url = signOrderNo ?
                  `https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/start_digital_sign?dingtalkUserId=${dingtalkUserId}&orderNo=${signOrderNo}&faceVideoPath=${encodeURIComponent(mp4Url)}`
                  :
                  `https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/start_digital_signs?dingtalkUserId=${dingtalkUserId}&orderNos=${signOrderNos}&faceVideoPath=${encodeURIComponent(mp4Url)}`
                let res = await fetch(url, {
                  method: 'GET',
                });
                const { data, code } = await res.json()
                this.loading = false
                if (data.code === 200) {
                  if (signOrderNo) {
                    window.location.href = `https://api.zjcxjc.cn/api/v1/doc/face_success?init=0&signRecordId=${data.data}`;
                    // window.location.href = `http://192.168.1.91:8000/api/v1/doc/face_success?init=0&signRecordId=${data.data}`;
                  } else {
                    window.location.href = `https://api.zjcxjc.cn/api/v1/doc/face_success?init=1&register=0`;
                    // window.location.href = `http://192.168.1.91:8000/api/v1/doc/face_success?init=1&register=0`;
                  }
                } else {
                  this.centerDialogVisible = true;
                  this.promptContent = '人脸识别已失败，请重新上传。'
                  this.currentAction = 'failedAction';
                }
              } else {
                const mp4Url = `${personInformationPath}face-base.mp4`
                const result = await client.put(mp4Url, file);
                let res = await fetch(`https://api.zjcxjc.cn/api/v1/digital-sign/intention/face-sign-up?userId=${userId}`, {
                  method: 'GET',
                });
                const { data } = await res.json()
                // window.location.href = `http://localhost:8000/api/v1/doc/face_success?init=1&register=1`;
                window.location.href = `https://api.zjcxjc.cn/api/v1/doc/face_success?init=1&register=1`;
              }
            } else {
              console.log('Failed to fetch data.');
            }
          } catch (error) {
            console.error('Upload to OSS failed:', error);
          }
        },
        openFullScreen2 () {
          const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
          })
          setTimeout(() => {
            loading.close()
          }, 5000)
        },
        createdAction () {
          this.centerDialogVisible = false;
          this.progress = 0
          this.startVideoRecording()
        },
        pendingAction () {
          this.centerDialogVisible = false;
          window.location.href = this.pendingUrl
        },
        signedAction () {
          this.centerDialogVisible = false;
          window.location.href = `https://api.zjcxjc.cn/api/v1/doc/face_success?init=1&register=0`;
        },
        failedAction () {
          this.centerDialogVisible = false;
          this.progress = 0
          this.startVideoRecording()
        },
      },
      async mounted () {
        if (signOrderNo) {
          const response = await fetch(`https://api.zjcxjc.cn/api/v1/digital-sign/get-sign-record?signOrderNo=${signOrderNo}&userId=${userId}`, {
            method: 'GET',
          });
          const { data, code } = await response.json();
          console.log(data)
          if (code === 200) {
            this.centerDialogVisible = true
            if (data.signStatus === 'CREATED') {
              this.promptContent = '订单已创建，请进行人脸识别'
              this.currentAction = 'createdAction';
            }
            if (data.signStatus === 'PENDING') {
              this.promptContent = '正在进行人脸识别中，请等待。'
              this.pendingUrl = `https://api.zjcxjc.cn/api/v1/doc/face_success?init=0&signRecordId=${data.id}`;
              this.currentAction = 'pendingAction';
            }
            if (data.signStatus === 'SIGNED') {
              this.promptContent = '人脸识别已成功，请勿重复上传。'
              // document.querySelector('#promptContent').innerText = '人脸识别已成功，请勿重复上传。'
              this.currentAction = 'signedAction';
            }
            if (data.signStatus === 'FAILED') {
              this.promptContent = '人脸识别已失败，请重新上传。'
              // document.querySelector('#promptContent').innerText = '人脸识别已失败，请重新上传。'
              this.currentAction = 'failedAction';
            }
          }
        } else {
          this.centerDialogVisible = false;
          this.progress = 0
          this.startVideoRecording()
        }
      }

    };
    const app = Vue.createApp(App);
    app.use(ElementPlus);
    app.mount("#app");
  </script>
</body>

</html>